package jnpf.task.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.github.pagehelper.PageHelper;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import jnpf.base.UserInfo;
import jnpf.base.model.ColumnDataModel;
import jnpf.base.service.SuperServiceImpl;
import jnpf.database.util.DynamicDataSourceUtil;
import jnpf.model.QueryAllModel;
import jnpf.permission.entity.UserEntity;
import jnpf.task.entity.TaskEntity;
import jnpf.task.mapper.TaskMapper;
import jnpf.task.model.task.TaskConstant;
import jnpf.task.model.task.TaskForm;
import jnpf.task.model.task.TaskPagination;
import jnpf.task.service.TaskService;
import jnpf.util.*;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 *
 * task
 * 版本： V3.6
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2024-11-08
 */
@Service
public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, TaskEntity> implements TaskService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Override
    public List<TaskEntity> getList(TaskPagination taskPagination){
        return getTypeList(taskPagination,taskPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<TaskEntity> getTypeList(TaskPagination taskPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("task",TaskEntity.class);

        MPJLambdaWrapper<TaskEntity> wrapper = JoinWrappers
                .lambda("task",TaskEntity.class)
                .selectAll(TaskEntity.class);
        MPJLambdaWrapper<TaskEntity> wrapper2 = JoinWrappers
                .lambda("task",TaskEntity.class)
                .distinct().selectAll(TaskEntity.class);

        QueryAllModel queryAllModel = new QueryAllModel();
        queryAllModel.setWrapper(wrapper);
        queryAllModel.setClassMap(tableClassMap);
        //数据过滤
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ?   TaskConstant.getAppColumnData() : TaskConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());
        queryAllModel.setRuleJson(ruleJson);
        //高级查询
        boolean hasSuperQuery =  true;
        if (hasSuperQuery) {
            queryAllModel.setSuperJson(taskPagination.getSuperQueryJson());
        }
        //数据权限
        boolean pcPermission = false;
        boolean appPermission = false;
        if (isPc && pcPermission && !userProvider.get().getIsAdministrator()) {
            queryAllModel.setModuleId(taskPagination.getMenuId());
        }
        if (!isPc && appPermission && !userProvider.get().getIsAdministrator()) {
            queryAllModel.setModuleId(taskPagination.getMenuId());
        }
        //拼接复杂条件
        wrapper = generaterSwapUtil.getConditionAllTable(queryAllModel);
        queryAllModel.setWrapper(wrapper2);
        wrapper2 = generaterSwapUtil.getConditionAllTable(queryAllModel);
        //其他条件拼接
        otherConditions(taskPagination, wrapper, isPc);
        otherConditions(taskPagination, wrapper2, isPc);

        if("0".equals(dataType)){
            com.github.pagehelper.Page<Object> objects = PageHelper.startPage((int) taskPagination.getCurrentPage(), (int) taskPagination.getPageSize(), true);
            List<TaskEntity> userIPage = this.selectJoinList(TaskEntity.class, wrapper2);
            List<Object> collect = userIPage.stream().map(t -> t.getId()).collect(Collectors.toList());
            if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(collect)){
                wrapper.in(TaskEntity::getId,collect);
            }
            List<TaskEntity> result = this.selectJoinList(TaskEntity.class, wrapper);
            return taskPagination.setData(result,objects.getTotal());
        }else{
            List<TaskEntity> list = this.selectJoinList(TaskEntity.class, wrapper);
            if("2".equals(dataType)){
                List<String> selectIds = Arrays.asList(taskPagination.getSelectIds());
                return list.stream().filter(t -> selectIds.contains(t.getId())).collect(Collectors.toList());
            }else{
                return list;
            }
        }

    }

    /**
    * 其他条件拼接
    */
    private void otherConditions(TaskPagination taskPagination, MPJLambdaWrapper<TaskEntity> wrapper, boolean isPc) {
        String databaseName;
        try {
            @Cleanup Connection cnn = DynamicDataSourceUtil.getCurrentConnection();
            databaseName = cnn.getMetaData().getDatabaseProductName().trim();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //关键词
        if(ObjectUtil.isNotEmpty(taskPagination.getJnpfKeyword())){
        }
        //普通查询
        if(isPc){
            if(ObjectUtil.isNotEmpty(taskPagination.getUrl())){
                String value = taskPagination.getUrl() instanceof List ?
                    JsonUtil.getObjectToString(taskPagination.getUrl()) :
                    String.valueOf(taskPagination.getUrl());
                wrapper.like(TaskEntity::getUrl,value);
            }

            if(ObjectUtil.isNotEmpty(taskPagination.getParam1())){
                String value = taskPagination.getParam1() instanceof List ?
                    JsonUtil.getObjectToString(taskPagination.getParam1()) :
                    String.valueOf(taskPagination.getParam1());
                wrapper.like(TaskEntity::getParam1,value);
            }

            if(ObjectUtil.isNotEmpty(taskPagination.getParam2())){
                String value = taskPagination.getParam2() instanceof List ?
                    JsonUtil.getObjectToString(taskPagination.getParam2()) :
                    String.valueOf(taskPagination.getParam2());
                wrapper.like(TaskEntity::getParam2,value);
            }

            if(ObjectUtil.isNotEmpty(taskPagination.getParam3())){
                String value = taskPagination.getParam3() instanceof List ?
                    JsonUtil.getObjectToString(taskPagination.getParam3()) :
                    String.valueOf(taskPagination.getParam3());
                wrapper.like(TaskEntity::getParam3,value);
            }

            if(ObjectUtil.isNotEmpty(taskPagination.getParam4())){
                String value = taskPagination.getParam4() instanceof List ?
                    JsonUtil.getObjectToString(taskPagination.getParam4()) :
                    String.valueOf(taskPagination.getParam4());
                wrapper.like(TaskEntity::getParam4,value);
            }

        }
        //排序
        if(StringUtil.isEmpty(taskPagination.getSidx())){
                wrapper.orderByDesc(TaskEntity::getId);
        }else{
            try {
                String[] split = taskPagination.getSidx().split(",");
                for(String sidx:split){
                TaskEntity taskEntity = new TaskEntity();
                    if (sidx.startsWith("-")) {
                        Field declaredField = taskEntity.getClass().getDeclaredField(sidx.substring(1));
                        declaredField.setAccessible(true);
                        wrapper.orderByDesc(declaredField.getAnnotation(TableField.class).value());
                    } else {
                        Field declaredField = taskEntity.getClass().getDeclaredField(sidx);
                        declaredField.setAccessible(true);
                        wrapper.orderByAsc(declaredField.getAnnotation(TableField.class).value());
                    }
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public TaskEntity getInfo(String id){
        MPJLambdaWrapper<TaskEntity> wrapper = JoinWrappers
                .lambda("task",TaskEntity.class)
                .selectAll(TaskEntity.class);
        wrapper.and(
            t->t.eq(TaskEntity::getId,id)
        );
        return this.selectJoinOne(TaskEntity.class,wrapper);
    }
    @Override
    public void create(TaskEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String id, TaskEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(TaskEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(TaskForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id="";
        String countRecover = "";
        if (isUp){
            id = form.getId();
        }
        //主表字段验证
                if(StringUtil.isEmpty(form.getUrl())){
                    return "url不能为空";
                }
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param taskForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(TaskForm taskForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        taskForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(TaskConstant.getFormData(),taskForm,TaskConstant.TABLERENAMES),TaskForm.class);
        TaskEntity entity = JsonUtil.getJsonToBean(taskForm, TaskEntity.class);
        if(isSave){
            entity.setId(RandomUtil.uuId());
        }
        this.saveOrUpdate(entity);

    }
}
